<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems as Emslib;
use app\common\model\User;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;
use think\Config;
use think\Session;
use think\Hook;


/**
 * 邮箱验证码接口
 */
class Ems extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 发送验证码
     *
     * @ApiMethod (POST)
     * @ApiParams (name="email", type="string", required=true, description="邮箱")
     * @ApiParams (name="event", type="string", required=true, description="事件名称")
     */
    public function send()
    {
        $email = $this->request->post("email");
        $event = $this->request->post("event");
        $event = $event ? $event : 'register';

        if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $this->error(__('邮箱格式错误'));
        }
        if (!preg_match("/^[a-z0-9_\-]{3,30}\$/i", $event)) {
            $this->error(__('事件名称错误'));
        }

        //发送前验证码
        if (config('fastadmin.user_api_captcha')) {

            if (!preg_match("/^[a-z0-9]{4,6}\$/i", $captcha)) {
                $this->error(__('验证码格式错误'));
            }

            if (!\think\Validate::is($captcha, 'captcha')) {
                $this->error("验证码不正确");
            }
        }

        $last = Emslib::get($email, $event);
        if ($last && time() - $last['createtime'] < 60) {
            $this->error(__('发送频繁'));
        }

        $ipSendTotal = \app\common\model\Ems::where(['ip' => $this->request->ip()])->whereTime('createtime', '-1 hours')->count();
        if ($ipSendTotal >= 5) {
            $this->error(__('发送频繁'));
        }

        if ($event) {
            $userinfo = User::getByEmail($email);
            if ($event == 'register' && $userinfo) {
                //已被注册
                $this->error(__('已被注册'));
            } elseif (in_array($event, ['changeemail']) && $userinfo) {
                //被占用
                $this->error(__('已被占用'));
            } elseif (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
                //未注册
                $this->error(__('未注册'));
            }
        }
        $ret = Emslib::send($email, null, $event);
        if ($ret) {
            $this->success(__('发送成功'));
        } else {
            $this->error(__('发送失败'));
        }
    }

    /**
     * 发送邮箱验证码
     * */
    /*public function sendemailcode(){
        $email = $this->request->post("email");
        if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $this->error(__('邮箱格式错误'));
        }
        $mail = new PHPMailer(true);

        try {
            // 服务器配置
            $mail->isSMTP();
            $mail->Host       = Config::get('smtp.host');
            $mail->SMTPAuth   = true;
            $mail->Username   = Config::get('smtp.username'); // 完整 Gmail 地址
            $mail->Password   = Config::get('smtp.password');    // 应用专用密码（无空格）
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // TLS 加密
            $mail->Port       = Config::get('smtp.prot');

            // 发件人必须与登录邮箱一致（否则会被 Google 拒绝）
            $mail->setFrom(Config::get('smtp.from'), Config::get('smtp.from_name'));
            $mail->addAddress($email, $email);
            //生成6位数的验证码
            $code=$this->getcode();

            Session::set('REGISTER_CODE', $code);
            // 内容
            $mail->isHTML(true);
            $mail->Subject = '注册验证码';
            $mail->Body    = '<b>您的注册验证码为：</b>'.$code.'</b>';
            $mail->send();
            $this->success(__('邮件发送成功'));
        } catch (Exception $e) {
            $this->error(__('邮件发送失败').$e->getMessage());
        }
    }*/

    public function sendemailcode(){
        $email = $this->request->post("email");
        if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $this->error(__('邮箱格式错误'));
        }

        $mail = new PHPMailer(true);
        try {
            // 服务器配置 - 使用587端口
            $mail->isSMTP();
            $mail->Host = 'smtp.qq.com';
            $mail->SMTPAuth = true;
            $mail->Username = '3906570020@qq.com';
            $mail->Password = 'ynfxafymcczicejf';
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // 使用STARTTLS
            $mail->Port = 587; // 587端口

            // 编码设置
            $mail->CharSet = 'UTF-8';
            $mail->SMTPOptions = array(
                'ssl' => array(
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true
                )
            );

            // 发件人配置
            $mail->setFrom('3906570020@qq.com', '合创成');
            $mail->addAddress($email);

            //生成验证码
            $code = $this->getcode();
            Session::set('REGISTER_CODE', $code);

            // 邮件内容
            $mail->isHTML(true);
            $mail->Subject = '注册验证码';
            $mail->Body = '<b>您的注册验证码为：</b>'.$code;
            $mail->AltBody = "您的注册验证码为：{$code}";

            $mail->send();
            $this->success(__('邮件发送成功'));
        } catch (Exception $e) {
            $this->error(__('邮件发送失败: ').$e->getMessage());
        }
    }

    public function getinvitecode(){
        $arr=['a','A','b','B','c','C','d','D','e','E','f','F','g','G','h','H','i','I','j','J','k','K','l','L','m','M',
            'n','N','o','P','p','P','q','Q','r','R','s','S','t','T','u','U','v','V','w','W','x','X','y','Y','z','Z',
            '0','1','2','3','4','5','6','7','8','9'];

        $max=count($arr)-1;
        $str='';
        for($i=0;$i<8;$i++){
            $str.=$arr[mt_rand(0,$max)];
        }
        return $str;
    }

    /**
     * @ApiInternal
     */
    public function getcode(){
        $code='';
        for($i=0;$i<6;$i++){
            $code.=mt_rand(0,9);
        }
        return $code;
    }

    /**
     * 验证验证码
     */
    public function verifyCode111()
    {
        $email = $this->request->post('email');
        $code = $this->request->post('code');

        $savedCode = Session::get('email_verify_code');
        $savedEmail = Session::get('email_verify_email');
        $savedTime = Session::get('email_verify_time');

        if (!$savedCode || !$savedEmail || !$savedTime) {
            $this->error('验证码不存在或已过期');
        }

        // 检查是否过期（10分钟）
        if (time() - $savedTime > 600) {
            Session::delete('email_verify_code');
            Session::delete('email_verify_email');
            Session::delete('email_verify_time');
            $this->error('验证码已过期');
        }

        // 检查邮箱和验证码
        if ($savedEmail !== $email || $savedCode !== $code) {
            $this->error('验证码错误');
        }

        // 验证成功，清除验证码
        Session::delete('email_verify_code');
        Session::delete('email_verify_email');
        Session::delete('email_verify_time');

        $this->success('验证成功');
    }

    /**
     * 检测验证码
     *
     * @ApiMethod (POST)
     * @ApiParams (name="email", type="string", required=true, description="邮箱")
     * @ApiParams (name="event", type="string", required=true, description="事件名称")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function check()
    {
        $email = $this->request->post("email");
        $event = $this->request->post("event");
        $event = $event ? $event : 'register';
        $captcha = $this->request->post("captcha");

        if (!$email || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $this->error(__('邮箱格式错误'));
        }
        if (!preg_match("/^[a-z0-9_\-]{3,30}\$/i", $event)) {
            $this->error(__('事件名称错误'));
        }

        if (!preg_match("/^[a-z0-9]{4,6}\$/i", $captcha)) {
            $this->error(__('验证码格式错误'));
        }

        if ($event) {
            $userinfo = User::getByEmail($email);
            if ($event == 'register' && $userinfo) {
                //已被注册
                $this->error(__('已被注册'));
            } elseif (in_array($event, ['changeemail']) && $userinfo) {
                //被占用
                $this->error(__('已被占用'));
            } elseif (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
                //未注册
                $this->error(__('未注册'));
            }
        }
        $ret = Emslib::check($email, $captcha, $event);
        if ($ret) {
            $this->success(__('成功'));
        } else {
            $this->error(__('验证码不正确'));
        }
    }
}
